<template>
  <div class="content-container">
    <el-form label-width="auto" :inline="true" class="demo-form-inline">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-form-item label="运单号" class="full-width">
            <el-input v-model="filters.trackingNumber" placeholder="请输入运单号" class="full-width"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="出发地" class="full-width">
            <el-input v-model="filters.origin" placeholder="请输入出发地" class="full-width"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="类型" class="full-width">
            <el-select v-model="filters.customerType" placeholder="请选择状态" class="full-width">
              <el-option label="全部" :value="null"></el-option>
              <el-option label="仓库" :value="0"></el-option>
              <el-option label="货品" :value="1"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item class="right full-width" label=" ">
            <el-button-group class="full-width">
              <el-button icon="search" type="primary" plain @click="search" style="width: 100%">查询</el-button>
            </el-button-group>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="divider"></div>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['LogisticsOrders:LogisticsOrders:export']"
        >导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleCreateSettlement"
          v-hasPermi="['settlement:settlement:add']"
          :disabled="!canCreateSettlement"
        >创建结算单</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <!-- 修改后的表格部分 -->
    <el-table :data="currentTableData"
              ref="table"
              style="width: 100%;
              flex: 1"
              :header-cell-style="{
                backgroundColor: '#f5f7fa',
                color: '#333',
                fontWeight: 'bold',
                textAlign: 'center',
                padding: '10px 0'
              }"
              :cell-style="{
                padding: '10px 0',
                textAlign: 'center'
              }"
              @selection-change="handleSelectionChange"
              :default-sort="{ prop: 'hireDate', order: 'descending' }">
      <el-table-column type="selection" :selectable="isSelectable" width="45"/>
      <el-table-column prop="trackingNumber" label="运输单号" width="120">
        <template v-slot="scope">
          <el-link type="primary" @click="openDetailDialog(scope.row)">{{ scope.row.trackingNumber }}
          </el-link>
        </template>
      </el-table-column>
      <el-table-column prop="origin" label="出发地" width="130"></el-table-column>
      <el-table-column prop="destination" label="目的地" width="130"></el-table-column>
      <el-table-column prop="customerType" label="类型" width="90">
        <template v-slot="scope">
          <el-tag
              :type="scope.row.customerType === 0 ? 'success' : scope.row.driverState === 1 ? 'warning' : 'danger'"
              disable-transitions>
            {{ scope.row.customerType === 0 ? '货品' : '商品' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="重量" width="90">
        <template v-slot="scope">
          <span>{{ scope.row.weight }}{{ scope.row.weightUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column label="体积" width="80">
        <template v-slot="scope">
          <span>{{ scope.row.size }}{{ scope.row.volumeUnit }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="transportQuantity" label="数量" width="70"/>
      <el-table-column prop="departureDate" label="预计到货日期" sortable width="140">
        <template v-slot="scope">
          <span>{{ formatDate(scope.row.departureDate) }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="state" label="状态" mid-width="60">
        <template v-slot="scope">
          <el-tag
              :type="scope.row.state === 0 ? 'danger' : scope.row.state === 1 ? 'warning' : scope.row.state === 2 ? 'info' : scope.row.state === 3 ? 'success' : 'primary'"
              disable-transitions>
            {{
              scope.row.state === 0 ? '待确认' : scope.row.state === 1 ? '待运营商确认' : scope.row.state === 2 ? '待配送' : scope.row.state === 3 ? '运输中' : '已送达'
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="物流商id" width="90">
        <template v-slot="scope">
          <span>{{ scope.row.logisticId }}</span>
        </template>
      </el-table-column>
      <el-table-column label="运费" align="right" width="100">
        <template v-slot="scope">
          <span>{{ scope.row.feeTemp }}元</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100">
        <template v-slot="scope">
          <el-button @click="openDetailDialog(scope.row)" type="text" icon="View" style="font-size: 13px">详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="table-bottom">
      <el-pagination
          background
          layout="total, prev, pager, next"
          :total="total"
          :page-size="pageSize"
          v-model:current-page="currentPage"
          @current-change="handleCurrentChange"
          class="fixed-pagination">
      </el-pagination>
    </div>

    <!-- 创建结算单对话框 -->
    <el-dialog title="创建结算单" v-model="settlementOpen" width="600px" append-to-body>
      <el-form ref="settlementRef" :model="settlementForm" :rules="settlementRules" label-width="100px">
        <el-form-item label="合作方编码" prop="partnerCode">
          <el-input v-model="settlementForm.partnerCode" placeholder="请输入合作方编码" disabled />
        </el-form-item>
        <el-form-item label="订单总金额" prop="orderAmount">
          <el-input v-model="settlementForm.orderAmount" placeholder="请输入结算总金额" disabled />
        </el-form-item>
        <el-form-item label="协议编码" prop="agreementCode">
          <el-input v-model="settlementForm.agreementCode" placeholder="请输入协议编码"disabled />
        </el-form-item>
        <el-form-item label="备注信息" prop="remark">
          <el-input v-model="settlementForm.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-divider content-position="center">结算详情信息</el-divider>
        <el-table :data="settlementDetailList" :row-class-name="rowSettlementDetailIndex" @selection-change="handleSettlementDetailSelectionChange" ref="settlementDetailTable">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="订单编码" align="center" prop="orderCode" />
          <el-table-column label="订单金额" align="center" prop="orderAmount" />
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitSettlementForm">确 定</el-button>
          <el-button @click="cancelSettlement">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
      

<script setup name="LogisticsOrders">
import { ref, reactive, toRefs, getCurrentInstance } from 'vue';
import { createSettlement } from "@/api/settled/record.js";
import { ElMessage } from "element-plus";
import { listOperatorTransport } from '@/api/delivery/operatorTransport.js';
import { getAgreementCodeByPartnerCode } from "@/api/settled/agreement.js";


const filters = reactive({
  trackingNumber: '',
  origin: '',
  destination: '',
  departureDate: [],
  state: null,
  customerType: null,
});

const { proxy } = getCurrentInstance();

const currentTableData = ref([]);
const LogisticsOrdersList = ref([]); // 物流订单列表
const loading = ref(true); // 加载状态
const showSearch = ref(true); // 是否显示搜索栏
const selectedOrders = ref([]); // 选中的订单
const total = ref(0); // 总条数
const settlementOpen = ref(false); // 结算单弹窗状态
const canCreateSettlement = ref(false); // 是否可以创建结算单

// 查询参数
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  trackingNumber: filters.trackingNumber,
  origin: filters.origin,
  destination: filters.destination,
  state: filters.state,
  customerType: filters.customerType,
  startDate: filters.departureDate.length ? formatDate(filters.departureDate[0]) : null,
  endDate: filters.departureDate.length ? formatDate(filters.departureDate[1]) : null,
});

// 结算单表单
const settlementForm = reactive({
  partnerCode: '',
  orderAmount: 0,
  settlementMethod: '',
  agreementCode: '',
  currencyUnit: '',
  taxRate: 0,
  taxAmount: 0,
  settlementStatus: '',
  remark: '',
});

// 结算单校验规则
const settlementRules = {
  agreementCode: [
    { required: true, message: "协议编码不能为空", trigger: "blur" }
  ],

};

// 结算详情列表
const settlementDetailList = ref([]);

/** 查询物流订单列表 */
function getList() {
  loading.value = true;
  listOperatorTransport(queryParams)
    .then(response => {
      console.log('接口返回数据:', response); // 调试信息
      if (response && response.data) {
        currentTableData.value = response.data; // 确保数据赋值给 currentTableData
        total.value = response.total;
      } else {
        ElMessage.warning("未获取到数据");
        currentTableData.value = []; // 如果没有数据，清空表格
      }
    })
    .catch(error => {
      ElMessage.error('获取物流订单失败');
      console.error('获取物流订单失败:', error);
    })
    .finally(() => {
      loading.value = false;
    });
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  Object.assign(queryParams, {
    pageNum: 1,
    pageSize: 10,
    trackingNumber: '',
    origin: '',
    destination: '',
    state: null,
    customerType: null,
    startDate: null,
    endDate: null,
  });
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  selectedOrders.value = selection;
  canCreateSettlement.value = selection.length > 0;

  if (selection.length > 0) {
    // 获取第一个选中订单的物流商编号
    const logisticId = selection[0].logisticId;

    // 检查所有选中订单是否属于同一个物流商
    canCreateSettlement.value = selection.every(order => order.logisticId === logisticId);

    // 设置结算单的物流商编号
    settlementForm.partnerCode = logisticId;

    // 计算选中订单的总金额
    settlementForm.orderAmount = selection.reduce((sum, order) => {
      const amount = parseFloat(order.feeTemp || 0); // 处理空值或无效值
      return sum + (isNaN(amount) ? 0 : amount); // 确保金额有效
    }, 0);
  } else {
    // 如果没有选中订单，重置结算单信息
    canCreateSettlement.value = false;
    settlementForm.partnerCode = '';
    settlementForm.orderAmount = 0;
  }
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('LogisticsOrders/LogisticsOrders/export', {
    ...queryParams
  }, `LogisticsOrders_${new Date().getTime()}.xlsx`);
}


// 创建结算单按钮操作
async function handleCreateSettlement() {
  if (selectedOrders.value.length === 0) {
    ElMessage.warning("请先选择订单");
    return;
  }

  settlementForm.partnerCode = selectedOrders.value[0].logisticId;


  try {
    // 调用获取协议编码的方法
    const response = await getAgreementCodeByPartnerCode(settlementForm.partnerCode);
    console.log("获取协议编码响应:", response); // 添加日志
    if (response.code === 200) {
      settlementForm.agreementCode = response.msg; // 确保 response.data.agreementCode 包含协议编码
    } else {
      ElMessage.error(response.msg || "获取协议编码失败");
      return;
    }
  } catch (error) {
    console.error("获取协议编码失败:", error);
    ElMessage.error("获取协议编码失败");
    return;
  }

  // 计算选中订单的总金额
  settlementForm.orderAmount = selectedOrders.value.reduce((sum, order) => sum + parseFloat(order.feeTemp || 0), 0);

  // 生成结算单编码（假设后端生成，这里可以留空或生成一个临时编码）
  const settlementCode = "SETTLEMENT-" + Date.now(); // 临时编码，实际应由后端生成
  settlementForm.settlementCode = settlementCode;

  // 设置结算单详情列表
  settlementDetailList.value = selectedOrders.value.map((order, index) => ({
    index: index + 1,
    orderCode: order.trackingNumber, // 订单编码
    orderAmount: order.feeTemp, // 订单金额
    settlementCode: settlementCode // 结算单编码
  }));

  // 打开结算单对话框
  settlementOpen.value = true;
}



// 取消创建结算单
function cancelSettlement() {
  settlementOpen.value = false;
  resetSettlementForm();
}

// 重置结算单表单
function resetSettlementForm() {
  Object.assign(settlementForm, {
    partnerCode: '',
    orderAmount: 0,
    settlementMethod: '',
    agreementCode: '',
    currencyUnit: '',
    taxRate: 0,
    taxAmount: 0,
    settlementStatus: '',
    remark: '',
  });
  settlementDetailList.value = [];
}


// 提交结算单表单
function submitSettlementForm() {
  proxy.$refs["settlementRef"].validate(valid => {
    if (valid) {
      // 构造提交数据
      const dataToSend = {
        ...settlementForm, // 结算单信息
        settlementDetailList: settlementDetailList.value // 结算明细列表
      };

      // 调用创建结算单接口
      createSettlement(dataToSend).then(response => {
        if (response.code === 200) {
          proxy.$modal.msgSuccess("结算单创建成功");
          settlementOpen.value = false; // 关闭对话框
          resetSettlementForm(); // 重置表单
          getList(); // 刷新列表
        } else {
          proxy.$modal.msgError(response.msg || "结算单创建失败");
        }
      }).catch(error => {
        proxy.$modal.msgError("结算单创建失败");
      });
    }
  });
}

// 行索引
function rowSettlementDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
  return '';
}

// 详情按钮操作
function handleDetail(row) {
  getLogisticsOrders(row.orderCode).then(response => {
    detailForm.value = response.data;
    detailTitle.value = `订单详情 - ${row.orderCode}`;
    detailOpen.value = true;
  });
}
function formatDate(value) {
  if (!value) return '';
  const date = new Date(value);
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  return `${year}-${month}-${day}`;
}

// 初始化加载数据
onMounted(() => {
  getList();
});
</script>

<style scoped>
.content-container {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.table-container {
  flex: 1;
  display: flex;
  flex-direction: column;
}

.el-table {
  flex: 1;
}
</style>